// Copyright (C) Kumo inc. and its affiliates.
// Author: Jeff.li lijippy@163.com
// All rights reserved.
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published
// by the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program.  If not, see <https://www.gnu.org/licenses/>.
//
#pragma once

#include <pollux/common/time/timer.h>

#include "melon/synchronized.h"
#include <melon/container/f14_map.h>
#include <melon/container/f14_set.h>

namespace kumo::pollux::cache {
    class AsyncDataCache;

    struct RawFileInfo {
        int64_t openTimeSec;
        bool removeInProgress;

        bool operator==(const RawFileInfo &other) {
            return openTimeSec == other.openTimeSec &&
                   removeInProgress == other.removeInProgress;
        }
    };

    struct CacheAgeStats {
        // Age in seconds of the oldest opened file loaded to the caches.
        int64_t maxAgeSecs{0};
    };

    /// A process-wide singleton to handle TTL of AsyncDataCache and SsdCache.
    class CacheTTLController {
    public:
        /// Create and return a singleton instance of CacheTTLController.
        static CacheTTLController *create(AsyncDataCache &cache) {
            if (instance_ == nullptr) {
                instance_ =
                        std::unique_ptr<CacheTTLController>(new CacheTTLController(cache));
            }
            return instance_.get();
        }

        /// Return the process-wide singleton instance of CacheTTLController if it has
        /// been created. Otherwise, return nullptr.
        static CacheTTLController *getInstance() {
            if (instance_ == nullptr) {
                return nullptr;
            }
            return instance_.get();
        }

        static void testingClear() {
            instance_ = nullptr;
        }

        /// Add file opening info for a file identified by fileNum. Return true if a
        /// new file entry is inserted, or if the existing file entry is updated
        /// while cache deletion for the file is in progress. Return false otherwise
        /// if the existing file entry is not updated.
        bool addOpenFileInfo(
            uint64_t fileNum,
            int64_t openTimeSec = getCurrentTimeSec());

        /// Compute age related stats of the cached files.
        CacheAgeStats getCacheAgeStats() const;

        void applyTTL(int64_t ttlSecs);

    private:
        /// A process-wide singleton instance of CacheTTLController.
        static std::unique_ptr<CacheTTLController> instance_;

    private:
        // Prevent creating a random instance of CacheTTLController.
        explicit CacheTTLController(AsyncDataCache &cache) : cache_(cache) {
        }

        melon::F14FastSet<uint64_t> getAndMarkAgedOutFiles(int64_t maxOpenTimeSecs);

        /// Clean up file entries with removeInProgress true but keep entries for
        /// fileNums in filesToRetain.
        void cleanUp(const melon::F14FastSet<uint64_t> &filesToRetain);

        void reset();

        AsyncDataCache &cache_;

        /// A Map of fileNum to RawFileInfo.
        melon::Synchronized<std::unordered_map<uint64_t, RawFileInfo> > fileInfoMap_;
    };
} // namespace kumo::pollux::cache
